package com.ouroboroswiki.core.content.xml;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.logging.Logger;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

import com.ouroboroswiki.core.AbstractContent;
import com.ouroboroswiki.core.Content;
import com.ouroboroswiki.core.ContentException;

public class XMLDOMContent extends AbstractContent {
	
	@SuppressWarnings("unused")
	private static final Logger log = Logger.getLogger(XMLDOMContent.class.getName());
	
	private Document document;
	private TransformerFactory transformerFactory;
	private Map<String, Content> childContent;
	private boolean autoIndent;
	
	public XMLDOMContent( Document document, TransformerFactory transformerFactory, Map<String, Content> childContent ) {
		this( document, transformerFactory );
		this.childContent = childContent;
	}
	
	public XMLDOMContent( Document document, TransformerFactory transformerFactory ) {
		this.document = document;
		this.transformerFactory = transformerFactory;
		this.setMimeType("text/xml");
		this.setExists(true);
		this.setDynamic(true);
	}

	
	public void setAutoIndent(boolean autoIndent) {
		this.autoIndent = autoIndent;
	}

	@Override
	public Map<String, Content> getChildContent() {
		return this.childContent;
	}

	@Override
	public void write( OutputStream outs ) throws IOException, ContentException {
		DOMSource source = new DOMSource( document );
		StreamResult result = new StreamResult(outs);
		Transformer transformer;
		try {
			transformer = transformerFactory.newTransformer();
		} catch( TransformerConfigurationException ex ) {
			throw new ContentException( "unable to create empty transformer "+transformerFactory, ex );
		}
		transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes");
		if( autoIndent ) {
			transformer.setOutputProperty( OutputKeys.INDENT, "yes");
		}
		try {
			transformer.transform(source, result);
		} catch( TransformerException ex ) {
			throw new ContentException( "unable to transform "+document, ex );
		}
	}

}
